package com.sczmgk.hotline_pzh.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.ClipboardManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.hxim.ChatMsgBean;
import com.sczmgk.hotline_pzh.utils.BitmapUtils;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.utils.UiUtilities;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 自定义聊天消息正文主View
 *
 */
@SuppressWarnings("deprecation")
public class ChatMessageView extends LinearLayout implements ChatMessageItem.Callback,View.OnLongClickListener{



    private static final String TAG = "ChatMessageView";

    /**
     * 发送状态，进度条
     */
    private ProgressBar progressBar;

    /**
     * 发送失败的标识
     */
    private ImageView sendFailView;

    /**
     * 自己的头像，发送消息的类型才显示，显示在右边
     */
    private RoundCornerImageView userheadRightContainer;

    /**
     * 对方的头像，接收消息的类型才显示，显示在左边
     */
    private RoundCornerImageView userheadLeftContainer;

    /**
     * 消息正文容器，发送消息需要右对齐，接收消息左对齐（包含进度条，内容）
     */
    private LinearLayout contentContainer;

    /**
     * 正文容器集合
     */
    private Map<String, ChatMessageItem> containers = new HashMap<String, ChatMessageItem>();

    /**
     * 当前界面聊天消息
     */
    private ChatMsgBean uiMessage;

    /**
     * 时间显示控件
     */
    private TextView showTimeView;
    private boolean longClickEnabled;

    /**
     * 聊天内容的容器（只有内容部分,不含发送状态，时间。。。。。。）
     */
    private ViewGroup itemContainer;
    private boolean longClickConvertEnabled;


    private EditText mEditText;
    private Context context;

    public ChatMessageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    /**
     * 添加至消息正文容器，一个消息类型只能对应一个
     *
     * @param item
     */
    private void addContentTypeView(ChatMessageItem item) {
        if (containers.containsKey(item.getViewType())) {
            throw new IllegalArgumentException("Repeat to add the message type(" + item.getViewType()+ ").");
        }
        containers.put(item.getViewType()+"", item);
        //设置长按的监听
        item.setCallback(this);

    }

    public void setDisabledType(Set<String> disabledSets) {
        if (disabledSets != null) {
            for (String type : disabledSets) {
                ChatMessageItem item = containers.get(type);
                item.setCallback(null);
                containers.remove(type);
                itemContainer.removeView((View) item);
            }
        }
    }

    /**
     * 完成填充时的加调 ，这里找到控件
     */
    @Override
    protected void onFinishInflate() {
        itemContainer = (FrameLayout) findViewById(R.id.fl_item_container);
        contentContainer = (LinearLayout) findViewById(R.id.ll_chat_content_container);
        progressBar = (ProgressBar) findViewById(R.id.pb_chat_loading);
        showTimeView = (TextView) findViewById(R.id.tv_show_time);
        userheadLeftContainer = (RoundCornerImageView) findViewById(R.id.userhead_left);
        userheadRightContainer = (RoundCornerImageView) findViewById(R.id.userhead_right);
        sendFailView = (ImageView)findViewById(R.id.iv_chat_send_msg_fail);

        sendFailView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onFuntionClick(v);
            }
        });


        //2.将各个类型的View加到集合
        ChatMessageItemTextView  textItem = (ChatMessageItemTextView)findViewById(R.id.item_text_container);

        addContentTypeView(textItem);//加入文字聊天的item
    }
    /**
     * 获取消息类型对应的view
     * 如：是文本类型，则返回文本的View
     * @param contentType  内容的类型
     *
     * @return
     */
    private ChatMessageItem getMessageView(int contentType) {
        // 取得set集合中的相就类型的View
        ChatMessageItem item = containers.get(contentType);
        if (item == null) {
            item = containers.get(ChatMsgBean.MSG_TYPE_TEXT+"");
        }
        return item;
    }
    @Override
    public OnLongClickListener getLongClickListener() {
        return itemLongClickListener;
    }

//    @Override
//    public RecordPlayController getRecordPlayController() {
//        return rpc;
//    }

    @Override
    public OnClickListener getResendClickListener() {
        return resendClickListener;
    }

    @Override
    public OnClickListener getRedownloadClickListener() {
        return redownloadClickListener;
    }

    @Override
    public void hideTime() {
        UiUtilities.setVisibilitySafe(showTimeView, GONE);
    }

    /**
     *设置编辑框
     */
    public void setEdiText(EditText et) {
        this.mEditText = et;
    }

    /**
     * 设置消息，替换view状态
     *
     * @param newUiMessage   根据newUiMessage的类型取得相应的View
     */
    public void setMessage(ChatMsgBean newUiMessage) {
        //根据 传入的值改变是切换为机器人，还是切换为人工
        if (uiMessage == newUiMessage) {
            return;
        }
        uiMessage = newUiMessage;
        //给各个控件设置TAG
        setTag(newUiMessage);
        sendFailView.setTag(newUiMessage);
        itemContainer.setTag(newUiMessage);
        userheadLeftContainer.setTag(newUiMessage);
        userheadRightContainer.setTag(newUiMessage);
        final ChatMessageItem mItemView = getMessageView(newUiMessage.getMsgtype());// 根据msg的类型返回相应的View

        //文字聊天信息
        ChatMessageItemTextView chatMessageItemTextView =  (ChatMessageItemTextView)mItemView ;
        //设置文字内容
        chatMessageItemTextView.setText(newUiMessage.getTextmsg());
        setMessageTime(newUiMessage);// 设置信息时间
        setHeadIcon(newUiMessage);// 设置头像
        // 设置头像及文字的信息（自已发的显示在右边，接收的放左边）
        setProtoAndHeadIconStatus(newUiMessage,mItemView);//
        setSendStatus(mItemView,newUiMessage);// 设置发送状态（进度条）

        for (ChatMessageItem container : containers.values()) {  // 迭代容器集合，将没有取到类型的隐藏
            UiUtilities.setVisibilitySafe((View) container,container == mItemView ? VISIBLE : GONE);
            container.setViewStatus(container == mItemView ? newUiMessage : null);
        }
    }

    /**
     * 设置显示消息时间
     */
    private void setMessageTime(ChatMsgBean uiMsg) {
        if (uiMsg.getMsgtime() != 0) {
            String formatTime = Tools.dateFormatTime(uiMsg.getMsgtime());
            showTimeView.setText(formatTime);
            UiUtilities.setVisibilitySafe(showTimeView, View.VISIBLE);
        } else {
            UiUtilities.setVisibilitySafe(showTimeView, View.GONE);
        }
    }

    /**
     * 根据传入的消息设置头像的图片
     *
     * @param newUiMessage
     */
    private void setHeadIcon(ChatMsgBean newUiMessage) {

        if(newUiMessage.getMsgdir() == ChatMsgBean.SELF){//0 为自已
            // TODO 取数据库的图片文件路径

            Bitmap bitmap = BitmapUtils.getBitmap(newUiMessage.getHeadUrl(), 100, 100);//取头像
            if(bitmap!= null ){
                userheadRightContainer.setImageBitmap(bitmap);
            }else{
                userheadRightContainer.setBackgroundResource(R.drawable.chat_default_user_header);
            }
        }else{
            // TODO
            userheadLeftContainer.setBackgroundResource(R.drawable.chat_online_header);
        }
    }

    /**
     * 设置消息的协议，发送消息居右显示，接收消息居左显示，并设置头像的显示
     *
     * @param uiMessage
     *            UI消息
     * @param item
     *            自定义消息类型的View（如文字，图片，视频，语音）
     */
    private void setProtoAndHeadIconStatus(ChatMsgBean uiMessage,ChatMessageItem item) {

        int userheadLeftVisible = View.GONE;
        int userheadRightVisible = View.GONE;
        int gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
        int backgroundResId = 0;
        if (uiMessage.getMsgdir() == ChatMsgBean.SELF) {
            // 自己发送的消息显示到右边
            userheadLeftVisible = INVISIBLE;
            userheadRightVisible = VISIBLE;
            gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
            backgroundResId = R.drawable.chat_right_bg;
        } else {
            //对方发的消息显示 到左边
            userheadLeftVisible = VISIBLE;
            userheadRightVisible = INVISIBLE;
            gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
            backgroundResId = R.drawable.chat_left_bg;
        }

        // 默认背景图片带padding，不需要显示背景时需要清除padding
        itemContainer.setBackgroundResource(item.isShowBackground() ? backgroundResId: 0);

        if (!item.isShowBackground()) {
            itemContainer.setPadding(0, 0, 0, 0);
        }
        // 设置布局方向
        if (item.isShowCenterInLayout()) {
            gravity = Gravity.CENTER;
        }
        contentContainer.setGravity(gravity);

        if (!item.isShowHeadIcon()) {
            userheadLeftVisible = GONE;
            userheadRightVisible = GONE;
        }
        //设置显示谁的头像
        UiUtilities.setVisibilitySafe(userheadLeftContainer,userheadLeftVisible);
        UiUtilities.setVisibilitySafe(userheadRightContainer,userheadRightVisible);
    }

    /**
     * 设置发送成功或失败状态的标识
     */
    private void setSendStatus(ChatMessageItem item, ChatMsgBean msg) {
//        UiUtilities.setVisibilitySafe(sendFailView, GONE);UiUtilities.setVisibilitySafe(progressBar, GONE);
        if (!item.isShowMessageStatus()) {
            UiUtilities.setVisibilitySafe(sendFailView, GONE);
            UiUtilities.setVisibilitySafe(progressBar, GONE);
            return;
        }
        if (ChatMsgBean.MSG_STATUS_SEND_FAIL == msg.getStatus()) {
            MyLog.d(TAG,"显示发送失败的图标");
            UiUtilities.setVisibilitySafe(sendFailView, VISIBLE);
            UiUtilities.setVisibilitySafe(progressBar, GONE);
        } else if (ChatMsgBean.MSG_STATUS_SENDING == msg.getStatus()) {
            MyLog.d(TAG,"只显示进度条");
            UiUtilities.setVisibilitySafe(sendFailView, GONE);
            UiUtilities.setVisibilitySafe(progressBar, VISIBLE);
        } else {

            MyLog.e(TAG,"隐藏发送状态图标");
            UiUtilities.setVisibilitySafe(sendFailView, GONE);UiUtilities.setVisibilitySafe(progressBar, GONE);
        }
    }

//    private OnResendListener onResendListener;
//
//    public void setOnResendListener(OnResendListener onResendListener){
//        this.onResendListener = onResendListener;
//    }

    @Override
    public boolean onLongClick(View v) {
        ChatMsgBean uiMessage = (ChatMsgBean) v.getTag();
        if (uiMessage == null) {
            return false;
        }

        // 长按显示 复制，转发，删除按钮
        PopupWindow popupWindow = new PopupWindow(View.inflate(getContext(), R.layout.long_click_menu, null));
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        View view = popupWindow.getContentView();
        setItemClickStatus(popupWindow, view, R.id.long_click_copy, uiMessage);
        setItemClickStatus(popupWindow, view, R.id.long_click_convrt, uiMessage);
        setItemClickStatus(popupWindow, view, R.id.long_click_delete, uiMessage);
        // 正文控件计算x,y坐标的数组
        int headViewHeight = getResources().getDimensionPixelSize(R.dimen.pahead_view_height);
        view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        int popViewHeight = view.getMeasuredHeight();
        int popViewWidth = view.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        Log.i("yy", "x:" + location[0] + ",y:" + location[1] + "," + v.getWidth() + "," + popViewWidth + ","
                + popViewHeight);
        int x = location[0] + (v.getWidth() - popViewWidth) / 2;
        int y = location[1] - popViewHeight;
        // 控件上面显示不下pop，显示在控件的下面
        if (location[1] - headViewHeight - popViewHeight <= 0) {
            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.chat_long_press_up_bg));
            y = location[1] + v.getHeight();
        } else {
            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.chat_long_press_down_bg));
        }
        popupWindow.showAtLocation(v, Gravity.TOP | Gravity.START, x, y);
        return true;
    }

    public interface OnResendListener{
        void onResend(ChatMsgBean msg);
    }
    /**
     * 功能点击事件
     * @param v
     */
    private void onFuntionClick(View v) {
        final ChatMsgBean uiMessage = (ChatMsgBean) v.getTag();
        if (uiMessage == null) {
            return;
        }

        switch (v.getId()) {
            case R.id.iv_chat_send_msg_fail://点击了发送失败的图标
                // 重发
                DialogFactory.chooseDialog(context, context.getResources().getString(R.string.chat_msg_isRepeat), context.getResources().getString(R.string.chat_msg_repeat),
                        new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //重发
                                ChatMsgBean message = (ChatMsgBean) sendFailView.getTag();
                                MyApp.hxImUtils.reSendTextMsg(message);
                            }
                        });
                break;
            case R.id.long_click_delete:
                // 删除
                Map<String,Object> maps = new HashMap<>();
                maps.put("chatid",uiMessage.getChatid());
                MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_DELETE_CHAT_MSG_URL, maps, MyHttp.POST, context, false, null, new SimplePaserJsonCallback() {
                    @Override
                    public void onVerifyIsNull() {
                        //删除本条消息
                        //更新列表

                    }

                    @Override
                    public void onVerifySuccess(String dataRaw, boolean isCache) {

                    }
                });
                break;
            case R.id.long_click_copy:
//                 拷贝
                ClipboardManager clip = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                clip.setText(uiMessage.getTextmsg());
                Toast.makeText(getContext(), R.string.copy_successful, Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }


    /**
     * 设置条目点击事件
     * @param popupWindow
     * @param view
     * @param resId
     * @param uiMessage
     */
    private void setItemClickStatus(final PopupWindow popupWindow, View view, int resId, ChatMsgBean uiMessage) {
        View v = view.findViewById(resId);
        if (v != null) {
            v.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    onFuntionClick(v);
                    popupWindow.dismiss();
                }
            });
            v.setTag(uiMessage);
        }
    }
    private OnLongClickListener itemLongClickListener = new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            MyLog.i(TAG, "onLongClick longClickEnabled:" + longClickEnabled);
            if (!longClickEnabled) {
                return false;
            }
            return ChatMessageView.this.onLongClick(itemContainer);
        }
    };

    /**
     * 设置是否激活长按功能
     */
    public void setLongClickEnabled(boolean enabled) {
        this.longClickEnabled = enabled;
    }

    /**
     * 设置是否激活长按转发功能
     */
    public void setLongClickConvertEnabled(boolean enabled) {
        this.longClickConvertEnabled = enabled;
    }
    private OnClickListener redownloadClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    };

    /**
     * 录音和录像的重发
     */
    private OnClickListener resendClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            onFuntionClick(sendFailView);
        }
    };

}